<?php
/**
 * Класс отвечает получение данных из БД
 *
 */
class Main{
	
	private $arrIds = array();
	private $arrFolders = array();
	
	/**
	 * получаем папки
	 *
	 */
	public static function getFolders(){
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT `folder`.`ID_folder`,
					 `folder`.`ID_root_folder`,
					 `folder`.`creation`,
					 `folder`.`name`
		FROM `folder`
		ORDER BY `folder`.`name`";
		return $objDB->select($stmt);
	}	

	/**
	 * получаем всю инфу о файле
	 */
	public static function getFileById($idFile){
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT *
		FROM `file`
		WHERE `file`.`ID_file` = " . $idFile;
		return $objDB->selectOne($stmt);		
	}
	
	/**
	 * получаем папки
	 *
	 */
	public static function getRootFolders($idFolder){
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT `folder`.`ID_folder`,
					 `folder`.`ID_root_folder`,
					 `folder`.`creation`,
					 `folder`.`name`
		FROM `folder`
		WHERE `folder`.`ID_root_folder` = " . $idFolder . "
		ORDER BY `folder`.`name`";
		return $objDB->select($stmt);
	}
	
	/**
	 * получаем файлы папки
	 *
	 */
	public static function getFiles($idFolder){
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT *
		FROM `file`
		WHERE `ID_folder` = " . $idFolder . "
		ORDER BY `file`.`name`";
		return $objDB->select($stmt);
	}
	
	/**
	 * получаем файлы по id папок
	 *
	 */
	public static function getFilesByFolderIds($arrFildersId){
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT `file`.`ID_file`,
					 `file`.`name`
		FROM `file`
		WHERE `ID_folder` IN(" . join($arrFildersId, ',') . ")
		ORDER BY `file`.`name`";
		$arrFiles = $objDB->select($stmt);
		$arrNewFiles = array();
		foreach ($arrFiles as $file){
			$arrNewFiles['ids'][] = $file['ID_file'];
			$arrNewFiles['names'][] = $file['name'];
		}
		return $arrNewFiles;
	}
	
	/**
	 * сохраняем файл
	 */
	public static function saveFile($arrFile, $folderId){
		echo '<pre>';
			print_r($arrFile);
		echo '</pre>';
		$objDB = Service_Database::instance();
		$stmt = "
		INSERT INTO `file` (`ID_folder`, `type`, `name`, `unique_name`, `size`, `creation`)
		VALUES (" . $folderId . ", '" . $arrFile['type'] . "', '" . $arrFile['name'] . "', '" . $arrFile['unique_name'] . "', " . $arrFile['size'] . ", '" . Service_Date::gLocalTime2BD() . "')";
		$objDB->query($stmt);
	}
	
	/**
	 * удаляем файлы
	 *
	 */
	public static function deleteFiles($arrFiles){
		self::deleteFilesFromFolder($arrFiles['unique_name']);
		self::deleteFilesFromDb($arrFiles['ids']);
		return true;
	}
	
	/**
	 * удаляем файлы с БД
	 *
	 */
	private static function deleteFilesFromDb($arrFilesIds){
		$objDB = Service_Database::instance();
		$stmt = "
		DELETE FROM `file`
		WHERE `file`.`ID_file` IN(" . join($arrFilesIds, ', ') . ")";
		return $objDB->query($stmt);
	}
	
	/**
	 * удаляем файлы из Папки
	 *
	 */
	private static function deleteFilesFromFolder($arrFilesNames){
		foreach ($arrFilesNames as $fileName)
			@unlink(ABSPATH . "content/upload_files/" . $fileName);
	}
	
	/**
	 * добавляем папку
	 */
	public static function createFolder($idFolder, $newFolderName){
		$objDB = Service_Database::instance();
		$stmt = "		
		INSERT INTO `folder` (`ID_root_folder`, `name`, `creation`)
		VALUES (" . ($idFolder == 0 ? "NULL" : $idFolder) . ", '" . $newFolderName . "', '" . Service_Date::gLocalTime2BD() . "')";
		//echo 
		return $objDB->queryInsertAutoincrement($stmt);
	}
	
	/**
	 * удалям папку
	 *
	 */
	public function deleteFolder($arrFolders){
		$this->arrFolders = self::getFolders();
		foreach ($arrFolders as $idFolder){
			$this->arrIds[] = $idFolder;
			$this->getChildIds($idFolder);			
		}
		$arrFildersId = $this->arrIds;
		$arrFiles = $this->getFilesByFolderIds($arrFildersId);
		
		if ($arrFiles){
			self::deleteFiles($arrFiles);
			self::deleteFoldersFromDb($arrFildersId);
		}
		self::deleteFoldersFromDb($arrFildersId);
		
	}
	
	/**
	 * удаляем попки из БД
	 */
	public static function deleteFoldersFromDb($arrFildersId){
		arsort($arrFildersId);
		$objDB = Service_Database::instance();
		//из-за ссылок нельзя удалить одним запросом - разобраться
		foreach ($arrFildersId as $idFolder){
			$stmt = " DELETE FROM `folder` WHERE `folder`.`ID_folder` = " . $idFolder . " LIMIT 1;";
			$objDB->query($stmt);
		}
	}
	
	/**
	 * получаем id потомков
	 *
	 */
	private function getChildIds($idFolder){
		foreach ($this->arrFolders as $folder){
			if ($folder['ID_root_folder'] == $idFolder){
				$this->arrIds[] = $folder['ID_folder'];
				$this->getChildIds($folder['ID_folder']);
			}				
		}			
	}
}
?>